import {Form, Button, Radio, Col, DatePicker, TimePicker} from 'antd';
import {WeaInput, WeaBrowser, WeaDialog, WeaNewScroll, WeaTableEdit } from 'ecCom';
import _transform from 'lodash/transform'
import * as Apis from '../../../apis/previewMeeting';
import moment from 'moment';
import "babel-polyfill";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;


const initialValue = {
    isattend: '1',
    bookroom: '2',
    bookticket: '2',
    begindate: undefined,
    begintime: undefined,
    roomstander: undefined,
    ticketstander: undefined,
    backdate: undefined,
    backtime: undefined,
    recRemark: undefined,
    othermember: undefined
};
class ReceiptForm extends React.Component {
    constructor(props) {
        super(props);
        let otherMembers = this.initOtherMembers(props);
        this.state = {
            otherMembers: otherMembers.next().value,
            otherMemberIds: otherMembers.next().value,
            crmDatas: []
        };
    }
    
    componentDidMount() {
        this.props.initFunc && this.props.initFunc(this);
    }
    
    componentWillReceiveProps(nextProps) {
        let otherMembersGen = this.initOtherMembers(nextProps),
            otherMembers = otherMembersGen.next().value,
            otherMemberIds = otherMembersGen.next().value;
        if (otherMemberIds != this.state.otherMemberIds) {
            this.setState({
                otherMembers: otherMembers,
                otherMemberIds: otherMemberIds
            });
        }
    }
    
    render() {
        const {form, outerColumns, record, type} = this.props;
        const {getFieldProps} = form;
        let formItems = this.getFormItems(outerColumns, getFieldProps, record);
    
        let columns_mock = [
            {
                title: '姓名', //列名
                dataIndex: 'name', //列的id 对应数据
                key: 'name', //前端渲染key值
                width: 50,
                com: [ //当前列中渲染的自定义组件
                    {type: 'INPUT', key: 'name', width: 50},
                ]
            },
            {
                title: '性别',
                dataIndex: 'sex',
                key: 'sex',
                width: 50,
                com: [ //当前列中渲染的组件库组件，目前支持 select input browser checkbox
                    {type: 'SELECT' ,key: 'sex', width: 50, options: [{ key: '1',selected: true, showname: '男性'},{ key: '2', showname:'女性'}]},
                ]
            },
            {
                title: '职务',
                dataIndex: 'occupation',
                key: 'occupation',
                width: 50,
                com: [
                    {type: 'INPUT', key: 'occupation', width: 50},
                ]
            },
            {
                title: '电话',
                dataIndex: 'tel',
                key: 'tel',
                width: 80,
                com: [
                    {type: 'INPUT', key: 'tel', width: 80},
                ]
            },
            {
                title: '手机',
                dataIndex: 'handset',
                key: 'handset',
                width: 100,
                com: [
                    {type: 'INPUT', key: 'handset', width: 100},
                ]
            },
            {
                title: '备注',
                dataIndex: 'desc',
                key: 'desc',
                width: 100,
                com: [
                    {type: 'INPUT', key: 'desc', width: 100},
                ]
            }
        ];
        return (
            <Form horizontal>
                {formItems}
                {type == 'hrm' ?
                    <FormItem labelCol={{span: 6}} wrapperCol={{span: 12}} label="其他参会人员:">
                        <WeaBrowser isSingle={false} linkUrl="/hrm/resource/HrmResource.jsp?id="
                                    title="多人力资源" type="17" viewAttr={2} onChange={this.changeOtherMember}
                                    replaceDatas={this.state.otherMembers}
                        />
                    </FormItem> :
    
                    <WeaTableEdit title="参会客户代表" columns={columns_mock} datas={this.state.crmDatas || []} onChange={this.changeCrmUser}
                                  viewAttr={2}
                    />
                }
            </Form>
        );
    }
    
    initOtherMembers = function*(props) {
        let list = props.otherMembers ? props.otherMembers.map((o) => {
            return {
                id: o.otherid,
                name: o.othername
            };
        }) : [];
        yield list;
        let ids = props.otherMembers ? props.otherMembers.reduce((sum, value) => {
            return sum ? (sum + "," + value.otherid) : value.otherid;
        }, "") : "";
        yield ids;
    }
    getFormItems = (outerColumns, getFieldProps, record) => {
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 14},
        };
        let formItems = [];
        formItems.push(
            <FormItem {...formItemLayout} label="是否参加:">
                <RadioGroup {...getFieldProps('isattend', {initialValue: '1'})}>
                    <Radio value="1">是</Radio>
                    <Radio value="2">否</Radio>
                </RadioGroup>
            </FormItem>
        );
        outerColumns && outerColumns.forEach((col) => {
            switch (col.key) {
                case "begindate":
                    formItems.push(
                        <FormItem {...formItemLayout} label="预计到达日期.时间:">
                            <Col span="10">
                                <FormItem>
                                    <DatePicker {...getFieldProps('begindate')} />
                                </FormItem>
                            </Col>
                            <Col span="2">
                                <p className="ant-form-split">-</p>
                            </Col>
                            <Col span="10">
                                <FormItem>
                                    <TimePicker {...getFieldProps('begintime')} format="HH:mm"/>
                                </FormItem>
                            </Col>
                        </FormItem>
                    );
                    break;
                case "bookroom":
                    formItems.push(
                        <FormItem {...formItemLayout} wrapperCol={{span: 12}} label="是否需订房(标准):">
                            <Col span="6">
                                <FormItem>
                                    <RadioGroup {...getFieldProps('bookroom', {initialValue: '2'})}>
                                        <Radio value="1">是</Radio>
                                        <Radio value="2">否</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col span="18">
                                <FormItem>
                                    <WeaInput {...getFieldProps('roomstander')} />
                                </FormItem>
                            </Col>
                        </FormItem>
                    );
                    break;
                case "bookticket":
                    formItems.push(
                        <FormItem {...formItemLayout} label="是否需订回程票:">
                            <RadioGroup {...getFieldProps('bookticket', {initialValue: '2'})}>
                                <Radio value="1">是</Radio>
                                <Radio value="2">否</Radio>
                            </RadioGroup>
                        </FormItem>
                    );
                    formItems.push(
                        <FormItem {...formItemLayout} label="交通工具:">
                            <RadioGroup {...getFieldProps('ticketstander')}>
                                <span className="trans-label">飞机</span>
                                <Radio value="1">头等舱</Radio>
                                <Radio value="2">公务舱</Radio>
                                <Radio value="3">经济舱</Radio>
                            </RadioGroup>
                            <RadioGroup {...getFieldProps('ticketstander')}>
                                <span className="trans-label">火车</span>
                                <Radio value="4">软卧</Radio>
                                <Radio value="5">硬卧</Radio>
                                <Radio value="6">硬座</Radio>
                            </RadioGroup>
                        </FormItem>
                    );
                    formItems.push(
                        <FormItem {...formItemLayout} label="回程日期.时间:">
                            <Col span="10">
                                <FormItem>
                                    <DatePicker {...getFieldProps('backdate')} />
                                </FormItem>
                            </Col>
                            <Col span="2">
                                <p className="ant-form-split">-</p>
                            </Col>
                            <Col span="10">
                                <FormItem>
                                    <TimePicker {...getFieldProps('backtime')} format="HH:mm"/>
                                </FormItem>
                            </Col>
                        </FormItem>
                    );
                    break;
                case "recRemark":
                    formItems.push(
                        <FormItem {...formItemLayout} label="备注信息:">
                            <WeaInput {...getFieldProps('recRemark')} />
                        </FormItem>
                    );
                    break;
                default:
                    break;
            }
        });
        return formItems;
    }
    changeOtherMember = (ids, names, users) => {
        this.setState({otherMemberIds: ids, otherMembers: users});
    }
    clear = () => {
        this.props.form.setFieldsValue(initialValue);
        this.setState({
            otherMembers: []
        });
    }
    
    getFormValue = function*() {
        let values = this.props.form.getFieldsValue();
        let {otherMemberIds, otherMembers, crmDatas} = this.state;
        values.othermember = otherMemberIds;
        Array.isArray(crmDatas) ? crmDatas.forEach((obj, idx) => {
        	for (let key in obj) {
                values[`${key}_${idx}`] = obj[key];
            }
        }) : [];
        yield values;
        yield otherMembers;
    }
    changeCrmUser = (datas,columns) => {
        this.setState({
            crmDatas: datas
        });
    }
}
ReceiptForm = Form.create({
    mapPropsToFields: (props) => {
        let result = _transform(props.record.values, (result, value, key) => {
            let trimValue = typeof (value) == 'string' ? value.trim() : value;
            if (["begindate", "backdate"].some((str) => str == key)) {
                if (!moment(value, "YYYY-MM-DD").isValid()) {
                    trimValue = "";
                }
            } else if (["begintime", "backtime"].some((str) => str == key)) {
                if (moment(value, "HH:mm").isValid()) {
                    trimValue = "";
                }
            }
            trimValue && ((result[key] || (result[key] = {})).value = trimValue);
        }, {});
        return result;
    }
})(ReceiptForm);

class MeetMemberReceiptDialog extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            record: {},
            type: "",//类型，标识客户还是员工
        };
        this.open = ::this.open;
    }
    
    render() {
        let {visible, record, type} = this.state;
        const {hrmcolumns, crmcolumns, meetingId} = this.props;
        const outerColumns = type == 'hrm' ? hrmcolumns : crmcolumns;
        return (
            <WeaDialog visible={visible} title="会议参与回执"
                       icon="icon-coms-meeting" iconBgcolor="#f14a2d"
                       style={{width: 650, height: 600}}
                       onCancel={this.back}
                       buttons={[
                           <Button type="primary" onClick={this.submit}>提交</Button>,
                           <Button type="primary" onClick={this.reset}>重置</Button>,
                       ]}>
                <div className="wea-meet-receipt-dialog">
                    <div className="panel-title">基本信息</div>
                    <WeaNewScroll>
                        <ReceiptForm outerColumns={outerColumns} meetingId={meetingId} record={record}
                                     ref="form" initFunc={(form) => this.form = form}
                                     otherMembers={record.othermember}
                                     type={type}
                        />
                    </WeaNewScroll>
                </div>
            </WeaDialog>
        );
    }
    
    open = (record, type) => {
        this.setState({
            visible: true,
            record: record,
            type: type
        });
    }
    
    back = () => {
        this.setState({
            visible: false,
            record: {}
        });
    }
    
    submit = () => {
        let formValues = this.form.getFormValue(),
            formValue = formValues.next().value,
            otherMembers = formValues.next().value;//暂时不使用这个值，不过先不改了。
        const {actions, meetingId} = this.props;
        const {record, type} = this.state;
        formValue.meetingid = meetingId;
        formValue.recorderid = record.recorderid;
        let parseDate = (date, format) => {
            if (date && moment.isDate(date)) {
                return moment(date).format(format);
            }
            return date;
        }
        formValue.begindate = parseDate(formValue.begindate, "YYYY-MM-DD");
        formValue.begintime = parseDate(formValue.begintime, "HH:mm");
        formValue.backdate = parseDate(formValue.backdate, "YYYY-MM-DD");
        formValue.backtime = parseDate(formValue.backtime, "HH:mm");
        formValue = _transform(formValue, (result, value, key) => {
            if (value) result[key] = value;
        }, {});
        let promise = type == "hrm" ? Apis.meetingReHrm(formValue) : Apis.meetingReCrm(formValue);
        promise.then(result => {
            actions.setNewReply(result, formValue, type, otherMembers);
            this.back();
        });
    }
    
    reset = () => {
        this.form.clear();
    }
    
}


export default MeetMemberReceiptDialog;